package service

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"week3/projectsrv/global"
	"week3/projectsrv/projectsrv"
)

func GetGoodsByPrice(sortId int) ([]*projectsrv.Goods, error) {
	var (
		err    error
		res    *elastic.SearchResult
		esMaps []map[string]interface{}
		list   []*projectsrv.Goods
	)
	es := global.EsClient.Search().Index(global.GOODS_ES_INDEX)
	switch sortId {
	case global.GOODS_SALES:
		res, err = es.Sort("goods_sales", false).Do(context.Background())
	case global.GOODS_PRICE:
		res, err = es.Sort("goods_price", false).Do(context.Background())
	default:
		res, err = es.Do(context.Background())
	}
	if err != nil {
		return nil, err
	}
	for _, hit := range res.Hits.Hits {
		var esMap map[string]interface{}
		json.Unmarshal(hit.Source, &esMap)
		for i, v := range hit.Highlight {
			esMap[i] = v[0]
		}
		esMaps = append(esMaps, esMap)
	}
	for _, s := range esMaps {
		list = append(list, &projectsrv.Goods{
			Id:         int32(s["id"].(float64)),
			GoodsName:  s["goods_name"].(string),
			GoodsPrice: float32(s["goods_price"].(float64)),
			GoodsStock: int32(s["goods_stock"].(float64)),
			GoodsDesc:  s["goods_desc"].(string),
			GoodsSales: int32(s["goods_sales"].(float64)),
		})
	}
	return list, nil
}
